<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" title="申请" width="50%" append-to-body>
      <el-form label-width="100">
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="applyData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <choose-table ref="chooseTable" :state="1"></choose-table>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="sub">提交</el-button>
          <el-button @click="close">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>


import api from "@/api/asset/apply.js";
import ChooseTable from "@/components/Asset/ChooseTable.vue";

const emit = defineEmits(['sub']);

const props = defineProps({
  applyType: {
    type: String,
    required: true,
  }
})

// 是否编辑
const isEdit = ref(false);

const applyDataInit = {
  id: null,
  applyType: props.applyType,
  remark: null,
}

const applyData = reactive({ ...applyDataInit });

const formDataInit = {
  targetUserId: null,
  remark: null
}

const tableData = reactive({
  loading: false,
  list: [], // 表格列表数据
});


const openFlag = ref(false);
const chooseTable = ref()

const formData = reactive({...formDataInit})

function reset() {
  Object.assign(applyData, applyDataInit);
  Object.assign(formData, formDataInit);
  tableData.list = [];
}

function open(row) {
  openFlag.value = true;
  reset();
  if (row) {
    api.detail(row).then(response=> {
      Object.assign(applyData, response);
      const resFormData = response.formData;
      if (resFormData) {
        Object.assign(formData, resFormData);
      }
      let relItems = formData.items;
      if (!relItems) {
        relItems = []
      }
      chooseTable.value.setList(relItems)

    })
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}


function getParams() {
  const apply = { ...applyData };
  apply.applyType = props.applyType;
  formData.items = chooseTable.value.getList();
  apply.formData = JSON.stringify(formData);
  return {
    edit: isEdit.value,
    apply: apply
  }
}

function check() {
  return new Promise((resolve, reject) => {
    resolve()
  })
}

/** 保存 */
function save() {
  check().then(()=> {
    api.save(getParams()).then(response => {
      emit("sub");
      close();
    });
  });
}

function sub() {
  check().then(()=> {
    api.saveAndSub(getParams()).then(response => {
      emit("sub");
      close();
    });
  });

}

defineExpose({
  open
})

</script>

